<template>
  <div>
    <unit-table
      :columns="this.isManager?this.$staticMenu.GJBDataColumns:this.$staticMenu.GJBDataNoActionColumns"
      :url="tableUrl"
      :type="tableType"
      selectType="checkbox"
      :params="tableParams"
      :selectedKeys="tableSelectedKeys"
      :size="pageSize"
      :sizeOptions="pageSizeOptions"
      rowKeyName="id"
      ref="unitTable"
      @onSelect="tableOnSelect"
    >
      <!-- 补充搜索条件 -->
      <a-row slot="searchCri">
        <a-col :span="4">
            <a-range-picker
              class="searchCriteria"
              v-model="time"
              @change="timeChange"
              />
        </a-col>
        <a-col :span="3">
          <a-input v-model="tableParams.fileName" class="searchCriteria" @keydown.native="keydown($event)" placeholder="文件名称" />
        </a-col>
        <a-col :span="3">
          <a-input v-model="tableParams.fileConfig" class="searchCriteria" @keydown.native="keydown($event)" placeholder="数据标识" />
        </a-col>
        <a-col :span="3">
          <a-select v-model="tableParams.scanLevel" class="searchCriteria">
            <a-select-option v-for="(item, key) of level"
                :value="item.value"
                :key='item.value'
            >{{item.label}}</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="3">
          <a-input v-model="tableParams.region" class="searchCriteria" placeholder="范围" />
        </a-col>
        <a-col :span="3">
          <a-select v-model="tableParams.status" class="searchCriteria"  v-if="this.isManager">
            <a-select-option
              v-for="(item, key) of fileStatus"
              :value="item.value"
              :key="item.value"
            >{{item.label}}</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="5" style="text-align: right;">
          <a-button type="primary" @click="criteriaSearch">
            <a-icon type="search" />查询
          </a-button>
          <a-button @click="clearCriteria">
            <a-icon type="sync" />重置
          </a-button>
        </a-col>
      </a-row>
      <!-- end -->
      <!-- 补充表格操作 -->
      <div class="actionBtn" slot="tableAct">
        <a-button type="primary" @click="importFile">
          <a-icon type="import" />导入
        </a-button>
        <a-button  @click="exportData">
          <a-icon type="download" />导出
        </a-button>
        <span style="float:right"  v-if="this.isManager&&approved=='未审批'">
          <a-button type="primary" class="btn-success" @click="acceptAll">
            <a-icon type="check" />审批通过
          </a-button>
          <a-button type="danger" @click="rejectAll">
            <a-icon type="close" />拒绝
          </a-button>
        </span>
      </div>
      <!-- end -->
      <!-- 补充表格每行的操作 -->
      <span slot="statusSwitch" slot-scope="props">
        <span v-if="props.record.status=='审批通过'" class="text-success">{{props.record.status}}</span>
        <span v-if="props.record.status=='审批拒绝'" class="text-danger">{{props.record.status}}</span>
        <span v-if="props.record.status=='未审批'">{{props.record.status}}</span>
      </span>
      <!-- 补充表格每行的操作 -->
      <span slot="tableRowAct" slot-scope="props">

<!--      <a-divider type="vertical" v-if="props.record.status=='未审批'" />-->
			<a @click="update(props.record)" v-if="props.record.status=='未审批'">
				<span class="ant-tag ant-tag-blue">
					<a-icon type="cloud-sync" /> 更新
				</span>
			</a>
<!--			<a-divider type="vertical" v-if="props.record.status=='未审批'" />-->
			<a v-if="props.record.status=='未审批'" @click="accept(props.record)">
				<span class="ant-tag ant-tag-green">
					<a-icon type="check" /> 审批通过
				</span>
			</a>
<!--      <a-divider type="vertical" v-if="props.record.status=='未审批'" />-->
			<a v-if="props.record.status=='未审批'" @click="reject(props.record)">
				<span class="ant-tag ant-tag-volcano">
					<a-icon type="close" /> 拒绝
				</span>
			</a>
<!--      <a-divider type="vertical"/>-->
			<a  @click="deletefile(props.record)">
				<span class="ant-tag ant-tag-volcano">
					<a-icon type="close" /> 删除
				</span>
			</a>
      </span>
    </unit-table>
    <modal
      ref="importModalForm"
      :action="fileAction"
      :param="uploadParam"
      :title="modalTitle"
      :type="opType"
      :validator="validatorForm"
      :visible="modalVisible"
      @cancel="handleCancel"
      @ok="handleOk"
    ></modal>
  </div>
</template>

<script>
import {
  APPROVALACCEPT,
  APPROVALDLETE,
  APPROVALREJECT,
  GETALLLIST,
  GETALLSTATUS,
  UPLOADFILE,
  UPLOADFILEUPDATE,
  GETALLACCEPTLIST
} from '@/../static/js/apis.js';
import unitTable from '@/common/table';
import global from '@/../static/global.vue';
import modal from './GJBModal';
import moment from 'moment';
import { importForm, importForm1 } from '@/../static/js/formValidators.js';
import _ from 'lodash'; // 引入lodash：封装了诸多对字符串，数组，对象等常见数据类型的处理函数
export default {
  inject: ['reload'],
  name: 'allUnit',
  components: {
    unitTable,
    modal
  },
  data() {
    return {
      time:[],
      level: [],
      fileStatus: [],
      treeSelectedKeys: '0',
      tableSelectedKeys: [],
      // tableUrl: GETALLLIST.url, // 调用表格组件，必须参数，后台数据接口
      tableType: GETALLLIST.type, // 调用表格组件，必须参数，后台方法方法（get，post）
      pageSize: 15,
      pageSizeOptions: ['15', '20', '40'],
      /* 调用表格组件，可选参数，其他相关搜索条件 */
      tableParams: {
        fileName: '',
        timeRange: [],
        fileConfig: '',
        scanLevel:'全部级别',
        region:'',
        status: '全部审批状态',
        menuId: this.$route.query.menuId
      },
      approved: '',
      modalTitle: '', // modal标题
      modalVisible: false, // modal关闭打开控制器
      uploadParam: {},
      fileAction: '', // 导入文件提交路径
      opType: '',
      validatorForm: importForm,
      userId: ''
    }
  },

  computed: {
    // 判断是否管理员
    isManager() {
      return global.isManager(global.SYS_DATA_MANAGE)
    },
    tableUrl () {
      return global.isManager(global.SYS_DATA_MANAGE)
        ? GETALLLIST.url
        : GETALLACCEPTLIST.url
    }
  },
  methods: {
    keydown(e){
      if(e.keyCode==32){
        e.returnValue=false
      }
    },
    /*获取静态数据*/
    getStaticData() {
      let self = this
      GETALLSTATUS('', function (res) {
        self.fileStatus = res.obj
      })
      this.level = this.$staticMenu.scanlevel
      this.userId = parseInt(localStorage.getItem("userid"));
    },
    timeChange(date, dateString) {
         this.tableParams.timeRange=dateString
    },
    /* 表格checkbox选中事件*/
    tableOnSelect (selectedRowKeys, selectedRows) {
      this.tableSelectedKeys = selectedRowKeys
    },
    /* 查询按钮*/
    criteriaSearch () {
      // this.$refs.unitTable.fetch(1)
      this.approved = this.tableParams.status
      this.$refs.unitTable.fetch(1)
    },
    /*重置按钮 */
    clearCriteria () {
      this.tableParams.fileName = ''
      this.tableParams.timeRange = []
      this.time=[]
      this.tableParams.fileConfig = ''
      this.tableParams.scanLevel = '全部级别'
      this.tableParams.region =''
      this.tableParams.status = '全部审批状态'
      this.$refs.unitTable.rowSelection.onChange([ ],[ ])
      this.criteriaSearch()
    },
    importFile () {
      this.opType = '新建';
      this.modalTitle = '导入文件';
      this.fileAction = UPLOADFILE.url
      this.uploadParam = {
        userId: this.userId
      }
      this.validatorForm = importForm
      this.modalVisible = true
    },
    update (record) {
      this.opType = '更新';
      this.modalTitle = record.fileName
      this.modalVisible = true
      this.fileAction = UPLOADFILEUPDATE.url
      this.uploadParam = {
        userId: this.userId,
        fileId: record.id
      }
      this.validatorForm = importForm1
      //form的setFieldsValue方法放入参数与form中对应，可少不可多，用以下方法进行筛选
      const pickArr = ['fileConfig', 'fileTime', 'scanLevel', 'regionList']
      const formShowInfo = _.pick(record, pickArr)
      formShowInfo.fileTime = moment(formShowInfo.fileTime, 'YYYY-MM-DD')
      //把数据放入modal，要在form加载完成后
      this.$nextTick(() => {
        this.$refs.importModalForm.form.setFieldsValue(formShowInfo)
      })
    },
    /*modal确定事件 */
    handleOk (e) {
      this.modalVisible = false
    },
    /* modal取消事件*/
    handleCancel (e) {
      this.modalVisible = false
    },
    exportData () {
      const selectedRowKeys = this.tableSelectedKeys
      if (selectedRowKeys.length > 0) {
        window.open(
          global.dataManUrl +
            '/rest/import/downloadMulFile?fileIds=' +
            selectedRowKeys
        )
      } else {
        this.$message.warning('请在表格中勾选要导出的数据！')
      }
    },
    acceptAll () {
      let self = this
      const selectedRowKeys = self.tableSelectedKeys
      var param = {
        ids: selectedRowKeys,
        userId: this.userId
      }
      if (selectedRowKeys.length > 0) {
        APPROVALACCEPT(param, function (res) {
          self.$message.success(res.message)
          self.reload()
        })
      } else {
        self.$message.warning('请在表格中勾选要审批的数据！')
      }
    },
    rejectAll () {
      let self = this
      const selectedRowKeys = self.tableSelectedKeys
      var param = {
        ids: selectedRowKeys,
        userId: this.userId
      }
      if (selectedRowKeys.length > 0) {
        APPROVALREJECT(param, function (res) {
          self.$message.success(res.message)
          self.reload()
        })
      } else {
        self.$message.warning('请在表格中勾选要审批的数据！')
      }
    },
    accept (record) {
      let self = this
      var param = {
        ids: [record.id],
        userId: this.userId
      }
      this.$confirm({
        title: '确定要通过该项吗?',
        content: '',
        onOk () {
          APPROVALACCEPT(param, function (res) {
            self.$message.success(res.message)
            self.reload()
          })
        }
      })

    },

    deletefile(record) {
      let self = this
      var param = {
        ids: [record.id],
        userId: this.userId
      }

      this.$confirm({
        title: '确定要删除该项吗?',
        content: '',
        onOk () {
          APPROVALDLETE(param, function (res) {
            self.$message.success(res.message)
            self.reload()
          })
        }
      })
    },
    reject (record) {
      let self = this
      var param = {
        ids: [record.id],
        userId: this.userId
      }
      this.$confirm({
        title: '确定要拒绝该项吗?',
        content: '',
        onOk () {
          APPROVALREJECT(param, function (res) {
          self.$message.success(res.message)
          self.reload()
        })
        }
      })

    }
  },

  created () {
    this.getStaticData()
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.searchCriteria{
	width:80%;
}
.actionBtn button:not(:last-child),
.ant-row button:not(:last-child) {
  margin-right: 20px;
}
.ant-tag{
  margin: 5px;
}
</style>
